﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Qs.Comm;
using Qs.App.Interface;
using Qs.App.Request;
using Qs.App.Response;
using Qs.Repository;
using Qs.Repository.Domain;
using Qs.Repository.Interface;


namespace Qs.App
{
    public class {ModuleCode} : {BaseAppName}<{ClassName},QsDBContext>
    {

        /// <summary>
        /// 加载列表
        /// </summary>
        public async Task<TableData> Load(Query{ClassName}ListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }
            
            var properties = loginContext.GetProperties("{ClassName}");
            
            if (properties == null || properties.Count == 0)
            {
                throw new Exception("当前登录用户没有访问该模块字段的权限，请联系管理员配置");
            }
                        
            var result = new TableData();
            var objs = GetDataPrivilege("u");
            if (!string.IsNullOrEmpty(request.key))
            {
                //增加筛选条件,如：
                //objs = objs.Where(u => u.Name.Contains(request.key));
            }
            
            var propertyStr = string.Join(',', properties.Select(u => u.Key));
            result.columnHeaders = properties;
            result.data = objs.OrderBy(u => u.Id)
            .Skip((request.page - 1) * request.limit)
            .Take(request.limit).Select($"new ({propertyStr})");
            result.count = objs.Count();
            return result;
        }

        public void Add(AddOrUpdate{ClassName}Req obj)
        {
            //程序类型取入口应用的名称，可以根据自己需要调整
            var addObj = obj.MapTo<{ClassName}>();
            //addObj.Time = DateTime.Now;
            Repository.Add(addObj);
        }
        
        public void Update(AddOrUpdate{ClassName}Req obj)
        {
            UnitWork.Update<{ClassName}>(u => u.Id == obj.Id, u => new {ClassName}
            {
               //todo:要修改的字段赋值
            });

        }

        public {ModuleCode}(IUnitWork<QsDBContext> unitWork, IRepository<{ClassName},QsDBContext> repository, IAuth auth) : base(unitWork, repository, auth)
        {
        }
    }
}